package LRU;

import java.util.*;

public class item146 {
    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        cache.put(1,1);
        cache.put(2,2);
        cache.get(1);
        cache.put(3,3);
        cache.get(2);
    }

}
class LRUCache {
    int maxSize=0;
    HashMap<Integer,Integer> map;
    int count =0;
    public LRUCache(int capacity) {
        this.maxSize =capacity;
        this.map = new LinkedHashMap<>();
    }

    public int get(int key) {
        if(map.containsKey(key))
        {
            makeRecentUse(key);
            return map.get(key);
        }
        return -1;
    }

    private void makeRecentUse(int key) {
        Integer val = map.get(key);
        map.remove(key);
        map.put(key,val);
    }

    public void put(int key, int value) {
        if(map.containsKey(key))
        {
            map.remove(key);
            map.put(key,value);
            return;
        }
        if(count>=this.maxSize)
        {
            Map.Entry<Integer, Integer> next = map.entrySet().iterator().next();
            map.remove(next.getKey());

        }
            map.put(key,value);
            count++;

    }
}